/*=====================================================
Critical Links
Auto Configuration Server

Authors:
	Rui Eduardo Gouveia Gil - r-gil@critical-links.com

Date: 2011
Version 0.1
=======================================================*/
ConfigurationPanel = function(configuration,parent) {
	this.configuration = configuration;
	this.parent = parent;

	this.configurationInformation = new Ext.Panel({
		layout: 'anchor',
        cls:'preview',
		border:false,
		region:'north',
		height: 350,
        minSize: 80,
        maxSize: 600,
        split: true,
        autoScroll: true,
        html: ''
    });

	this.deviceList = new Ext.grid.GridPanel({
        title: 'Devices assigned to this configuration',
        region: 'center',
        border: false,
        split: true,
        columns: [{ header: '', width: 30, renderer: this.renderStatus, dataIndex: 'Status', sortable: true, fixed: true},
        		  { header: "Name", dataIndex: 'Name', width: 320, sortable: true},
        		  { header: "Ip", dataIndex: 'Ip', width: 90, sortable: true, fixed: true},
        		  { header: "Release", dataIndex: 'Release', width: 120, sortable: true},
        		  { header: "Group", dataIndex: 'Group', width: 100, sortable: true},
        		  { header: "Last Contact On", dataIndex: 'LastContactOn', width: 120, sortable: true, fixed: true},
        		  { header: "License", dataIndex: 'License', width: 110, sortable: true, fixed: true},
        		  { header: "Customer", dataIndex: 'Customer', width: 150, sortable: true}],
        store: new Ext.data.ArrayStore({fields: ['Status','Name','Ip','Release','Group','LastContactOn','License','Customer','Device']})
    });
    
    this.deviceList.store.setDefaultSort('LastContactOn', "DESC");

    ConfigurationPanel.superclass.constructor.call(this, {
        closable: true,
		layout: 'border',
    	autoDestroy: true,
        id: this.configuration.tid,
    	iconCls:'configuration-icon',
        title: this.configuration.text,
        tabTip: this.configuration.description,
        items: [this.configurationInformation,this.deviceList],
        loadMask: {msg:'Loading Feed...'},
		tbar:[{text:'Edit Configuration', tooltip: {title:'Edit the configuration.'}, iconCls: 'edit-configuration-icon', handler: this.showEditConfiguration, scope:this },
			  {text:'Upload', tooltip: {title:'Upload configuration file'}, iconCls: 'upload-configuration-icon', handler: this.showUploadFile, scope:this },
        	  {split:false, text:'Apply to...', tooltip: {title:'Apply configuration to...'}, iconCls:'apply-configuration-icon', menu:{cls:'acs-menu', width:120, 
					items: [{text: 'Apply to groups', handler: this.showApplyGroups, scope: this, iconCls:'group-icon'},
							{text: 'Apply to devices', handler: this.showApplyDevices, scope: this, iconCls:'device-icon'}]}},
        	  {text:'Refresh', tooltip: {title:'Refresh'}, iconCls: 'refresh-list-icon', handler: this.refreshPanel, scope:this }]
    });

	this.gsm = this.deviceList.getSelectionModel();
    this.gsm.on('rowselect', this.onRowSelect, this);

    this.deviceList.on('rowdblclick', this.onRowDblClick, this);
    this.deviceList.on('rowcontextmenu', this.onRowContextMenu, this);
	
	this.addEvents({upload:true,apply:true});
	
	this.on('close', this.onClose, this);
	this.task = Ext.TaskMgr.start({run: this.onTimer, interval: 60000, scope: this});
 };

Ext.extend(ConfigurationPanel, Ext.Panel, {	
	onClose : function(device) {
		Ext.TaskMgr.stop(this.task);
	},	

	refresh : function(configuration) {
		if(configuration) {
			this.onTimer();
		} else {
			this.refreshPanel();
		}
	},

	showEditConfiguration : function(){
        if(!this.winConfiguration){
            this.winConfiguration = new ConfigurationWindow();
            this.winConfiguration.on('validconfiguration', this.cbShowEditConfiguration, this);
        }

        this.winConfiguration.show(this.configuration);
	},
	
	cbShowEditConfiguration : function(xml){
		this.configuration = new Configuration(xml);
		this.setTitle(this.configuration.name);
		this.updateConfigurationHTML();
       	this.parent.fireEvent('refreshtree');
	},

	showUploadFile : function() {
        if(!this.winUpload){
            this.winUpload = new ConfigurationUploadWindow(this.configuration);
            this.winUpload.on('upload', this.upload, this);
        }

        this.winUpload.show();
	},
	
	upload : function() {
		SGui.getConfiguration(this.configuration.id,this.cbTimerConfiguration,this);
		SGui.getConfigurationDevices(this.configuration.id,this.cbTimerDevices,this);
	},	

	showApplyGroups : function() {
        if(!this.winApply){
            this.winApply = new ConfigurationApplyWindow(this.configuration);
            this.winApply.on('apply', this.apply, this);
        }

        this.winApply.show(0);
	},	

	showApplyDevices : function() {
        if(!this.winApply){
            this.winApply = new ConfigurationApplyWindow(this.configuration);
            this.winApply.on('apply', this.apply, this);
        }

        this.winApply.show(1);
	},	
	
	apply : function() {
        this.parent.fireEvent('refresh');
        this.parent.fireEvent('refreshtree');
	},	

	updateConfiguration : function(configuration) {
		this.configuration = configuration;
		this.updateConfigurationHTML();
	},	

	onTimer : function() {
		SGui.getConfiguration(this.configuration.id,this.cbTimerConfiguration,this);
		SGui.getConfigurationDevices(this.configuration.id,this.cbTimerDevices,this);
	},	
	
	cbTimerConfiguration : function(obj,result){
		if(result) {	
			if(result instanceof Array) {			
				if(result[0] == '0' ) {
					Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
					
				} else {
					obj.configuration = new Configuration(result[1]);
					obj.updateConfigurationHTML();
				}				
			} else {
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
			}
		}
	},
	
	cbTimerDevices : function(obj,result){
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateDevice(result[i]);
			} else {
				obj.updateDevice(result);
			}
		}
	},

	onRowContextMenu : function(grid, index, e){
        if(!this.menu){ 
            this.menu = new Ext.menu.Menu({
                items: [{
                    iconCls:'open-device-icon',
                    text:'Open',
                    scope: this,
                    handler: this.contextOpen
                }]
            });
            
            this.menu.on('hide', this.onContextHide, this);
        }

        e.stopEvent();
 
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }

        this.ctxRow = this.deviceList.view.getRow(index);
        this.ctxRecord = this.deviceList.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        
        this.menu.showAt(e.getXY());
	},

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },
	
	contextOpen : function(){
		this.deviceSelected = this.ctxRecord.get('Device');
		this.openDevice();
	},

	onRowSelect : function(sm, index, record){
		this.deviceSelected = record.get('Device');
	},
	
	onRowDblClick : function(record){
		record = (record && record.data) ? record : this.gsm.getSelected();
		this.deviceSelected = record.get('Device');
		this.openDevice();		
	},

	showNewDevice : function(){
        if(!this.winDevice){
            this.winDevice = new DeviceWindow(this.configuration);
            this.winDevice.on('validdevice', this.updateDevice, this);
        }

        this.winDevice.show();
	},
	
	openDevice : function(){
		this.parent.load(this.deviceSelected);
	},

	refreshPanel : function() {
		this.deviceSelected = 0;
		SGui.getConfigurationDevices(this.configuration.id,this.cbRefreshDevices,this);
		if(this.deviceList.el)
			this.deviceList.el.mask('Loading Devices...', 'x-mask-loading');
		
		SGui.getConfiguration(this.configuration.id,this.cbRefreshConfiguration,this);	
		if(this.configurationInformation.el)
			this.configurationInformation.el.mask('Loading Devices...', 'x-mask-loading');
	},

	cbRefreshDevices : function(obj,result){
		obj.deviceList.store.removeAll();
		obj.deviceSelected = 0;
		if(result) {	
			if(result instanceof Array) {			
				for(var i=0; i<result.length; i++)
					obj.updateDevice(result[i]);
			} else {
				obj.updateDevice(result);
			}
		}
		if(obj.deviceList.el)
			obj.deviceList.el.unmask();
	},	
	
	cbRefreshConfiguration : function(obj,result){
		if(result) {	
			if(result instanceof Array) {			
				if(result[0] == '0' ) {
					Ext.MessageBox.show({title: 'Error', msg: result[1], buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
					
				} else {
					obj.configuration = new Configuration(result[1]);
					obj.setTitle(obj.configuration.name);
					obj.updateConfigurationHTML();
				}				
			} else {
				Ext.MessageBox.show({title: 'Error', msg: 'Protocol Error! Please check the logs for more information.', buttons: Ext.MessageBox.OK, icon: Ext.MessageBox.ERROR});
			}
		}
		if(obj.configurationInformation.el)
			obj.configurationInformation.el.unmask();
	},

	updateDevice : function(xml) {
		var device = new Device(xml);
		
		for(var i=0; i<this.deviceList.store.getCount(); i++) {
			if(this.deviceList.store.getAt(i).get('Device').id == device.id) {
				this.deviceList.store.getAt(i).set('Status',device.status);
				this.deviceList.store.getAt(i).set('Name',device.name);
				this.deviceList.store.getAt(i).set('Ip',device.ip);
				this.deviceList.store.getAt(i).set('Release',device.release);
				this.deviceList.store.getAt(i).set('Group',device.groupName);
				this.deviceList.store.getAt(i).set('LastContactOn',device.contactedStr);
				this.deviceList.store.getAt(i).set('License',device.licenseID);
				this.deviceList.store.getAt(i).set('Customer',device.customerName);
				this.deviceList.store.getAt(i).set('Device',device);
				return;
			}
		}		
		
		this.deviceList.store.loadData([[device.status,device.name,device.ip,device.release,device.groupName,device.contactedStr,device.licenseID,device.customerName,device]],true);
	},
	
	updateConfigurationHTML : function(){
		var html = "";
		
		html += "<div style=\"padding: 10px 0px 0px 10px;\">"
		html += "	<div style=\"padding-top: 5px;\"><table><tr><td><img src=\"icons/panel-configuration.png\"/></td><td valign=\"middle\">&nbsp;&nbsp;<span class=\"headText\">"+this.configuration.name+"</span></td></tr></table></div>";
		html += "	<div style=\"padding-top: 10px;\"><span class=\"lableText\">Created On:&nbsp;</span><span class=\"text\">"+this.configuration.creationStr+"</span></div>";
		html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Updated On:&nbsp;</span><span class=\"text\">"+this.configuration.updatedStr+"</span></div>";
		if(this.configuration.rwan == '1')
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Restore WAN configuration:&nbsp;</span><span class=\"text\">yes</span></div>";
		else
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Restore WAN configuration:&nbsp;</span><span class=\"text\">no</span></div>";
		if(this.configuration.rusers == '1')
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Restore Users:&nbsp;</span><span class=\"text\">yes</span></div>";
		else
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Restore Users:&nbsp;</span><span class=\"text\">no</span></div>";
		html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Used in:&nbsp;</span><span class=\"text\">"+this.configuration.deviceCount+" devices</span></div>";
		html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Description:&nbsp;</span><span class=\"text\">"+this.configuration.description+"</span></div>";
		if(this.configuration.configFileName != '')
		{
			html += "	<div style=\"padding-top: 15px;\"><span class='subheadText'>Backup Information</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">File Name:&nbsp;</span><span class=\"text\">"+this.configuration.configFileName+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Release:&nbsp;</span><span class=\"text\">"+this.configuration.cfRelease+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Type:&nbsp;</span><span class=\"text\">"+this.configuration.cfType+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Size:&nbsp;</span><span class=\"text\">"+this.configuration.cfSize+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">File created on:&nbsp;</span><span class=\"text\">"+this.configuration.cfCreation+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Master license:&nbsp;</span><span class=\"text\">"+this.configuration.cfLicenseID+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">With voip sounds:&nbsp;</span><span class=\"text\">"+this.configuration.cfVoipSounds+"</span></div>";
			html += "	<div style=\"padding-top: 5px;\"><span class=\"lableText\">Backup description:&nbsp;</span><span class=\"text\">"+this.configuration.cfDescription+"</span></div>";
		}
		html += "</div>"

		this.configurationInformation.update(html);
	},

	renderStatus : function(status, metadata){
		if(status == 0) { //DS_PENDING_VALIDATION
			metadata.attr = 'ext:qtip="pending validation"';
			return '<img src=icons/ledyellow.png>';
		} else if(status == 1) { //DS_PENDING_CONFIRMATION
			metadata.attr = 'ext:qtip="pending confirmation"';
			return '<img src=icons/ledyellow.png>';
		} else if(status == 2) { //DS_PENDING_BACKUP_WITH_SOUNDS
			metadata.attr = 'ext:qtip="pending backup with voip sounds"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 3) { //DS_PENDING_BACKUP
			metadata.attr = 'ext:qtip="pending backup"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 4) { //DS_PENDING_TASKS
			metadata.attr = 'ext:qtip="pending tasks"';
			return '<img src=icons/ledorange.png>';
		} else if(status == 5) { //DS_EXECUTING_BACKUP
			metadata.attr = 'ext:qtip="executing backup"';
			return '<img src=icons/ledblue.png>';
		} else if(status == 6) { //DS_EXECUTING_TASKS
			metadata.attr = 'ext:qtip="executing tasks"';
			return '<img src=icons/ledblue.png>';
		} else if(status == 7) { //DS_SYNCHRONIZED
			metadata.attr = 'ext:qtip="online"';
			return '<img src=icons/ledgreen.png>';
		} else {
			metadata.attr = 'ext:qtip="offline"';
			return '<img src=icons/ledgrey.png>';
		}
	}
});

Ext.reg('appconfigurationpanel', ConfigurationPanel);